package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IAppointmentService;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl extends ServiceImpl<StatementItemMapper,StatementItem> implements IStatementItemService {

    @Resource
    private StatementItemMapper statementItemMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private IAppointmentService appointmentService;


    /*
    select id, statement_id, item_id, item_name, item_price, item_quantity
      from bus_statement_item where statement_id = #{statementId}
     */
    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo, Long statementId) {
        IPage<StatementItem> page = new Page<>(qo.getPageNum(), qo.getPageSize());
        LambdaQueryWrapper<StatementItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StatementItem::getStatementId,statementId);
        return new TablePageInfo<>(super.page(page,wrapper));
    }


    @Override
    public boolean save(StatementItem statementItem) {
        statementItemMapper.insert(statementItem);
        return true;
    }


    @Override
    public StatementItem get(Long id) {
        //select id, statement_id, item_id, item_name, item_price, item_quantity
        //    from bus_statement_item
        //    where id = #{id}
        return statementItemMapper.selectById(id);
    }


    @Override
    public void update(StatementItem statementItem) {
        statementItemMapper.updateById(statementItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            statementItemMapper.deleteById(dictId);
        }
    }

    @Override
    public List<StatementItem> list() {
        return statementItemMapper.selectList(null);
    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> statementItems) {
        StatementItem statementItem = statementItems.remove(statementItems.size() - 1);
        BigDecimal discountAmount = statementItem.getItemPrice();
        Statement statement = statementService.get(statementItem.getStatementId());
        //如果当前状态是已支付，则不能在编辑
        if (statement.getStatus().equals(Statement.STATUS_PAID)) {
            throw new BusinessException("当前状态不是消费中，不能进行编辑");
        }
        //删除之前的明细项
        statementItemMapper.deleteById(statement.getId());
        //计算整个明细的总金额和总数量
        BigDecimal totalAmount = new BigDecimal("0.00");
        BigDecimal totalQuantity = new BigDecimal("0.00");
        if (statementItems.size() > 0) {
            //说明有明细项
            for (StatementItem item : statementItems) {
                //把每个结算单对象保存在数据库中
                statementItemMapper.insert(item);
                //计算总金额
                totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
                //计算总数量
                totalQuantity = totalQuantity.add(item.getItemQuantity());
            }
        }
        //如果单前的优惠金额大于总金额是不合法的
        if (totalAmount.compareTo(discountAmount) < 0) {
            throw new BusinessException("非法操作，当前的优惠金额大于总金额");
        }
        statementService.updateAmount(statement.getId(), totalAmount, totalQuantity, discountAmount);
    }

    @Override
    @Transactional
    public void payStatement(Long statementId) {
        Statement statement = statementService.get(statementId);
        if (statement.getStatus().equals(Statement.STATUS_PAID)) {
            throw new BusinessException("结算单已经支付，不能再重复支付");
        }
        User user = ShiroUtils.getUser();
        //支付声明
        statementService.payStatement(statementId, user.getId(), Statement.STATUS_PAID);

        if (statement.getAppointmentId() != null) {
            //使命该结算单是预约单生成的
            //把预约单的状态修改一下
            appointmentService.updateStatus(statement.getAppointmentId(), Appointment.STATUS_SETTLE);
        }
    }


    @Override
    public void deleteItemsByStatementId(Long statementId) {
        statementItemMapper.deleteById(statementId);
    }

    @Override
    public Workbook export(Long statementId) throws ParseException {
        Statement statement = statementService.get(statementId);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算明细单");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("客户姓名");
        row.createCell(1).setCellValue("联系方式");
        row.createCell(2).setCellValue("车牌号码");
        row.createCell(3).setCellValue("汽车类型");
        row.createCell(4).setCellValue("服务类型");
        row.createCell(5).setCellValue("到店时间");
        row.createCell(6).setCellValue("总消费金额");
        row.createCell(7).setCellValue("服务项数量");
        row.createCell(8).setCellValue("优惠金额");
        row.createCell(9).setCellValue("实付金额");
        row.createCell(10).setCellValue("收款人");
        row.createCell(11).setCellValue("收款时间");
        row.createCell(12).setCellValue("备注信息");

        Row row1 = sheet.createRow(1);
        SimpleDateFormat DataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        row1.createCell(0).setCellValue(statement.getCustomerName());
        row1.createCell(1).setCellValue(statement.getCustomerPhone());
        row1.createCell(2).setCellValue(statement.getLicensePlate());
        row1.createCell(3).setCellValue(statement.getCarSeries());
        row1.createCell(4).setCellValue(statement.getServiceType());
        if (DataFormat.format(statement.getActualArrivalTime()) == null){
            throw new BusinessException("当前到店时间为空，请处理一下，防止信息不明确");
        }
        row1.createCell(5).setCellValue(DataFormat.format(statement.getActualArrivalTime()));

        row1.createCell(6).setCellValue(statement.getTotalAmount().toPlainString());
        row1.createCell(7).setCellValue(statement.getTotalQuantity().toPlainString());
        row1.createCell(8).setCellValue(statement.getDiscountAmount().toPlainString());
        row1.createCell(9).setCellValue(statement.getTotalAmount().subtract(statement.getDiscountAmount()).toPlainString());
        row1.createCell(10).setCellValue(ShiroUtils.getUser().getUserName());
        if (DataFormat.format(statement.getPayTime()) == null){
            throw new BusinessException("当前收款人时间为空，请处理一下，防止信息不明确");
        }
        row1.createCell(11).setCellValue(DataFormat.format(statement.getPayTime()));

        row1.createCell(12).setCellValue(statement.getInfo());

        return workbook;
    }
}
